import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import pool from '@/lib/db';
import crypto from 'crypto';

export async function POST(request) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    // 查询用户ID
    const { rows } = await pool.query('SELECT id FROM users WHERE email = $1', [session.user.email]);
    const userId = rows[0]?.id;
    if (!userId) {
      return NextResponse.json({ error: '用户不存在' }, { status: 401 });
    }

    const { sourceId } = await request.json();

    // 获取要复制的提示词
    const sourceResult = await pool.query(
      'SELECT * FROM prompts WHERE id = $1 AND is_public = true',
      [sourceId]
    );

    if (sourceResult.rows.length === 0) {
      return NextResponse.json({ error: 'Prompt not found or not public' }, { status: 404 });
    }

    const sourcePrompt = sourceResult.rows[0];

    // 检查用户是否是原创建者
    if (sourcePrompt.user_id === userId) {
      return NextResponse.json({ error: 'Cannot copy your own prompt' }, { status: 400 });
    }

    // 创建新的提示词副本
    const newPromptData = {
      id: crypto.randomUUID(),
      title: sourcePrompt.title,
      content: sourcePrompt.content,
      description: sourcePrompt.description,
      tags: sourcePrompt.tags,
      version: '1.0.0', // 重置版本为1.0.0
      user_id: userId,
      is_public: false, // 复制的提示词默认为私有
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
      cover_img: sourcePrompt.cover_img
    };

    const result = await pool.query(
      `INSERT INTO prompts (id, title, content, description, tags, version, user_id, is_public, created_at, updated_at, cover_img) 
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) 
       RETURNING *`,
      [
        newPromptData.id,
        newPromptData.title,
        newPromptData.content,
        newPromptData.description,
        newPromptData.tags,
        newPromptData.version,
        newPromptData.user_id,
        newPromptData.is_public,
        newPromptData.created_at,
        newPromptData.updated_at,
        newPromptData.cover_img
      ]
    );

    const newPrompt = result.rows[0];

    return NextResponse.json({ 
      message: 'Prompt copied successfully',
      prompt: newPrompt
    });
  } catch (error) {
    console.error('Database error:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
} 